<?php
// archivos necesarios
require_once('./php_lib/conexion.php');

switch($_GET['funcion']) {
	case 1: // INSERT
		$query = sprintf("INSERT INTO Producto (prod_valor, tip_id, col_id, talla_id, mod_id, perfc_id) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
			$_POST['prod_valor'],
			$_POST['tip_id'],
			$_POST['col_id'],
			$_POST['talla_id'],
			$_POST['mod_id'],
			$_POST['perfc_id']);
  
		if( mysql_query($query, $db_zapatos) == TRUE) {
			$prod_id = mysql_insert_id();
			$fp = fopen($_POST['url_img'], 'r');
			$data = fread($fp, filesize($_POST['url_img']));
			$data = addslashes($data);
			//$data = str_replace('##','##',mysql_escape_string($data));
			fclose($fp);

			$query = sprintf("INSERT INTO `Imagen`(`ima_blob`, `ima_des`, `prod_id`) VALUES ('%s', '%s', '%s')",
				$data,
				$_POST['ima_des'],
				$prod_id);
				
			if( mysql_query($query, $db_zapatos) == TRUE) {
				if($_POST['borrar_img'] != 0) {
					unlink($_POST['url_img']);
				}
				$jsondata['respuesta'] = 1;
			} else {
				$error['insert'] = mysql_error();
				//$error['q'] = $query;
			}
		} else 
			$error['insert'] = mysql_error();
		
		break;
	case 2: // UPDATE
		// Inserto los datos de registro en la db
		$query = sprintf("UPDATE Producto SET prod_valor = '%s', tip_id = '%s', col_id = '%s', talla_id = '%s', mod_id = '%s', perfc_id = '%s' WHERE prod_id = %s;",
				$_POST['prod_valor'],
				$_POST['tip_id'],
				$_POST['col_id'],
				$_POST['talla_id'],
				$_POST['mod_id'],
				$_POST['perfc_id'],
				$_POST['prod_id']);
		if( mysql_query($query, $db_zapatos) == FALSE) 
			$error['update'] = mysql_error();			//$error['update'] = "Ocurrio un error al intertar guardar los cambios.";
		else {
			if($_POST['cambiar_img'] != 0) {
				$fp = fopen($_POST['url_img'], 'r');
				$data = fread($fp, filesize($_POST['url_img']));
				//$data = addslashes($data);
				$data = str_replace('##','##',mysql_escape_string($data));
				fclose($fp);

				$query = sprintf("UPDATE `Imagen` SET `ima_blob` = '%s' , `ima_des` = '%s' WHERE prod_id = '%s';",
					$data,
					$_POST['ima_des'],
					$_POST['prod_id']);
				if( mysql_query($query, $db_zapatos) == TRUE) {
					//if($_POST['borrar_img'] != 0) {
					unlink($_POST['url_img']);
					//}
					$jsondata['respuesta'] = 1;
				} else {
					$error['insert'] = mysql_error();
				}
			}
		}
		break;
	case 3: // DELETE
		$query = "DELETE FROM Producto WHERE prod_id = ".$_POST['prod_id'].";";
		$resultado = mysql_query($query, $db_zapatos);
		//	and mysql_query("DELETE FROM Producto WHERE prod_id = ".$_POST['prod_id'].";", $db_zapatos);
		if($resultado == TRUE){
			$jsondata['respuesta'] = 1;
		} else {
			$error['delete'] = "Error -- ocurrio un error al intentar borrar.";
			$error['error_mysql'] = mysql_error();
			$error['q'] = $query;
		}
		break;
	case 4: // SELECT
		$query = "SELECT * FROM Producto NATURAL LEFT JOIN Color NATURAL LEFT JOIN Talla NATURAL LEFT JOIN Modelo NATURAL LEFT JOIN Marca NATURAL LEFT JOIN Tipo NATURAL LEFT JOIN Perfil_Cliente NATURAL LEFT JOIN Genero NATURAL LEFT JOIN Pro_Sec NATURAL LEFT JOIN Sector NATURAL LEFT JOIN Bodega NATURAL LEFT JOIN Sucursal NATURAL LEFT JOIN Localidad NATURAL LEFT JOIN Region WHERE 1";
		
		if(isset($_POST['col_id']) && $_POST['col_id'] != 0) 
			$query .= " AND col_id = ".$_POST['col_id'];

		if(isset($_POST['talla_id']) && $_POST['talla_id'] != 0) 
			$query.= " AND talla_id = ".$_POST['talla_id'];

		if(isset($_POST['mar_id']) && $_POST['mar_id'] != 0) 
			$query .= " AND mar_id = ".$_POST['mar_id'];
		elseif(isset($_POST['mod_id']) && $_POST['mod_id'] != 0) 
			$query.= " AND mod_id = ".$_POST['mod_id'];

		if(isset($_POST['tip_id']) && $_POST['tip_id'] != 0) 
			$query .= " AND tip_id = ".$_POST['tip_id'];

		if(isset($_POST['perfc_id']) && $_POST['perfc_id'] != 0) 
			$query .= " AND perfc_id = ".$_POST['perfc_id'];
		elseif(isset($_POST['gen_id']) && $_POST['gen_id'] != 0) 
			$query.= " AND gen_id = ".$_POST['gen_id'];
		
		if(isset($_POST['suc_id']) && $_POST['suc_id'] != 0) 
			$query .= " AND suc_id = ".$_POST['suc_id'];
		elseif(isset($_POST['loc_id']) && $_POST['loc_id'] != 0) 
			$query .= " AND loc_id = ".$_POST['loc_id'];
		elseif(isset($_POST['reg_id']) && $_POST['reg_id'] != 0) 
			$query.= " AND reg_id = ".$_POST['reg_id'];

		$query .= " ORDER BY ".$_POST['orden']." ".$_POST['osentido']." LIMIT ".$_POST['inicio'].", ".$_POST['tam']." ";
		$query .= ";";  
		$resultado = mysql_query ($query, $db_zapatos);
		
		if( !$resultado) { 
			$error['query'] = 'Error al traer los datos desde la base.'; 
			break;
		}

		$jsondata['num_rows'] = mysql_num_rows($resultado);
		if( $jsondata['num_rows'] == 0) break;

		for($i = 0; $i < $jsondata['num_rows']; $i++) 
			$jsondata['rows'][$i] = mysql_fetch_assoc($resultado);
		break;
	case 5: // SELECT
		//if( $_POST['columnas'] == 0)	$columnas = "*";
		//if( $_POST['restriccion'] == 0)
		$key = $_POST['key'];
		$val = $_POST['val'];
//		$ignorar = $_POST['ignorar'];

		$query = "SELECT DISTINCT ".$key.", ".$val." FROM Producto NATURAL LEFT JOIN Color NATURAL LEFT JOIN Talla NATURAL LEFT JOIN Modelo NATURAL LEFT JOIN Marca NATURAL LEFT JOIN Tipo NATURAL LEFT JOIN Perfil_Cliente NATURAL LEFT JOIN Genero NATURAL LEFT JOIN Pro_Sec NATURAL LEFT JOIN Sector NATURAL LEFT JOIN Bodega NATURAL LEFT JOIN Sucursal NATURAL LEFT JOIN Localidad NATURAL LEFT JOIN Region WHERE 1";
		
		if($_POST['col_id'] != 0) 
			$query .= " AND col_id = ".$_POST['col_id'];

		if($_POST['talla_id'] != 0) 
			$query.= " AND talla_id = ".$_POST['talla_id'];

		if($_POST['mar_id'] != 0) 
			$query .= " AND mar_id = ".$_POST['mar_id'];
		elseif($_POST['mod_id'] != 0) 
			$query.= " AND mod_id = ".$_POST['mod_id'];

		if($_POST['tip_id'] != 0) 
			$query .= " AND tip_id = ".$_POST['tip_id'];

		if($_POST['perfc_id'] != 0) 
			$query .= " AND perfc_id = ".$_POST['perfc_id'];
		elseif($_POST['gen_id'] != 0) 
			$query.= " AND gen_id = ".$_POST['gen_id'];

		if($_POST['loc_id'] != 0) 
			$query .= " AND loc_id = ".$_POST['loc_id'];
		elseif($_POST['reg_id'] != 0) 
			$query.= " AND reg_id = ".$_POST['reg_id'];

		$query .= " ORDER BY ".$_POST['orden']." ".$_POST['osentido']." LIMIT ".$_POST['inicio'].", ".$_POST['tam']." ";
		$query .= ";";  
		$resultado = mysql_query ($query, $db_zapatos);
		
		if( !$resultado) { 
			$error['query'] = 'Error al traer los datos desde la base.'; 
			break;
		}

		$jsondata['num_rows'] = mysql_num_rows($resultado);
		if( $jsondata['num_rows'] == 0) break;

		for($i = 0; $i < $jsondata['num_rows']; $i++) 
			$jsondata['rows'][$i] = mysql_fetch_assoc($resultado);
		break;
	default:
		$error['error'] = 'Error -- funcion desconocida.';
}

if( !empty( $error)) {
	$jsondata['error'] = 1;
	$jsondata['lista_errores'] = $error;
} else 
	$jsondata['error'] = 0;
echo json_encode($jsondata);
?>